package com.datviet.dao.impl;

import java.util.List;

import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.datviet.dao.IPostDAO;
import com.datviet.entity.Post;

@Repository
public class PostDAO extends GenericDAO<Post> implements IPostDAO {

	@Override
	public List<Post> findLastedPost(String... searchingKeyword) {
		StringBuilder stringBuilder = new StringBuilder("SELECT p FROM Post p");
		String parameterName = "searchingKeyword";
		
		for (int i = 0; i < searchingKeyword.length; i++) {
			if(i == 0) {
				stringBuilder.append(" WHERE LOWER(p.text) LIKE :" + parameterName + i);
			} else {
				stringBuilder.append(" or LOWER(p.text) LIKE :" + parameterName + i);
			}						
		}
		stringBuilder.append(" ORDER BY p.modifiedAt DESC");
		TypedQuery<Post> query = getEntityManager().createQuery(stringBuilder.toString(), Post.class);
		
		for (int i = 0; i < searchingKeyword.length; i++) {
			query.setParameter(parameterName + i, "%" +  searchingKeyword[i].toLowerCase().trim() + "%");			
		}		
		query.setFirstResult(0);
		query.setMaxResults(20);
		
		return query.getResultList();
	}

}
